const pool = require('../models/db');
const bcrypt = require('bcrypt');

const userController = {
    // 获取所有用户
    getAllUsers: async (req, res) => {
        try {
            const [users] = await pool.query(
                'SELECT id, username, email, avatar_url, bio, location, created_at FROM users'
            );
            res.json(users);
        } catch (error) {
            res.status(500).json({ error: error.message });
        }
    },

    // 获取单个用户
    getUserById: async (req, res) => {
        try {
            const [user] = await pool.query(
                'SELECT id, username, email, avatar_url, bio, location, created_at FROM users WHERE id = ?',
                [req.params.id]
            );
            if (user.length === 0) {
                return res.status(404).json({ message: '用户不存在' });
            }
            res.json(user[0]);
        } catch (error) {
            res.status(500).json({ error: error.message });
        }
    },

    // 注册
    register: async (req, res) => {
        try {
            const { username, password, email, bio, location } = req.body;
            const hashedPassword = await bcrypt.hash(password, 10);
            
            const [result] = await pool.query(
                'INSERT INTO users (username, password, email, bio, location) VALUES (?, ?, ?, ?, ?)',
                [username, hashedPassword, email, bio, location]
            );
            
            res.status(201).json({
                message: '注册成功',
                userId: result.insertId
            });
        } catch (error) {
            if (error.code === 'ER_DUP_ENTRY') {
                return res.status(400).json({ message: '用户名或邮箱已存在' });
            }
            res.status(500).json({ error: error.message });
        }
    },

    // 登录
    login: async (req, res) => {
        try {
            const { username, password } = req.body;
            const [users] = await pool.query(
                'SELECT * FROM users WHERE username = ?',
                [username]
            );

            if (users.length === 0) {
                return res.status(401).json({ message: '用户名或密码错误' });
            }

            const user = users[0];
            const isValid = await bcrypt.compare(password, user.password);

            if (!isValid) {
                return res.status(401).json({ message: '用户名或密码错误' });
            }

            // 这里可以添加JWT token生成逻辑
            res.json({
                message: '登录成功',
                user: {
                    id: user.id,
                    username: user.username,
                    email: user.email
                }
            });
        } catch (error) {
            res.status(500).json({ error: error.message });
        }
    },

    // 更新用户
    updateUser: async (req, res) => {
        try {
            const { username, email, bio, location, avatar_url } = req.body;
            const [result] = await pool.query(
                `UPDATE users 
                SET username = ?, email = ?, bio = ?, location = ?, avatar_url = ?
                WHERE id = ?`,
                [username, email, bio, location, avatar_url, req.params.id]
            );

            if (result.affectedRows === 0) {
                return res.status(404).json({ message: '用户不存在' });
            }

            res.json({ message: '更新成功' });
        } catch (error) {
            if (error.code === 'ER_DUP_ENTRY') {
                return res.status(400).json({ message: '用户名或邮箱已存在' });
            }
            res.status(500).json({ error: error.message });
        }
    },

    // 删除用户
    deleteUser: async (req, res) => {
        try {
            const [result] = await pool.query(
                'DELETE FROM users WHERE id = ?',
                [req.params.id]
            );

            if (result.affectedRows === 0) {
                return res.status(404).json({ message: '用户不存在' });
            }

            res.json({ message: '删除成功' });
        } catch (error) {
            res.status(500).json({ error: error.message });
        }
    }
};

module.exports = userController;